
import 'package:palyer/app/components/toast_widget.dart';
import 'package:palyer/app/core/constans/error_code.dart';
import 'package:palyer/app/core/utils/string_util.dart';

import 'pagination.dart';

export 'pagination.dart';

class Result<T> {
  Result(this.code, this.msg, this.data, {this.errorData, this.pagination})
      : _status = code == ErrorCodeConstants.success ? HttpStatus.succeed : HttpStatus.failed;

  Result.success(this.data, {this.code = ErrorCodeConstants.success, this.msg = '成功', this.pagination}) : _status = HttpStatus.succeed;

  Result.fail(this.code, this.msg, {this.errorData}) : _status = HttpStatus.failed;

  final HttpStatus _status;

  bool get isSucceed => _status == HttpStatus.succeed;

  bool get isFailed => _status == HttpStatus.failed && code != ErrorCodeConstants.cancel;

  bool get isCancelled => _status == HttpStatus.failed && code == ErrorCodeConstants.cancel;

  late int code;
  late String msg;
  T? data;
  Pagination? pagination;

  dynamic errorData;

  void onSuccess(ResultCallBack<T> callBack) {
    if (isSucceed) {
      callBack.call(this);
    }
  }

  void onError(ResultCallBack<T> callBack) {
    if (isFailed) {
      callBack.call(this);
    }
  }

  void onCancel(ResultCallBack<T> callBack) {
    if (isCancelled) {
      callBack.call(this);
    }
  }

  void showErrorToast() {
    if (StringUtil.isNotBlank(msg)) {
      // Fluttertoast.showToast(msg: msg);
      AppToast.show(msg);
    }
  }
}

enum HttpStatus { succeed, failed }

typedef ResultCallBack<T> = void Function(Result<T> result);
